/**
 * Created by zhaojm on 15/3/28.
 */
game.BackgroundLayer = cc.Layer.extend({
    _bgImgList:null,

    _bgList : null,


    ctor:function () {
        this._super();
        this._bgList = [];

        var size = cc.winSize;


        this._bgImgList = [res.bg01_jpg];


        for(;;){
            var h = this.addOneBackground();
            if( this._bgList.length * h >= size.height * 2 && this._bgList.length >= 2){
                break;
            }
        }

        this.runAction(new cc.MoveBy(3, cc.p(0, -48)));

        this.schedule(this.roll, 3, cc.REPEAT_FOREVER, 0);
    },


    roll:function(){
        //var eyeX = this.parent.heroLayer.getEyeX();
        this.runAction(new cc.MoveBy(3, cc.p(0, -48)));


        while(true){

            if(this._bgList[0].getPositionY() + this._bgList[0].getContentSize().height <= -this.getPositionY()){

                var bg = this._bgList[0];

                this._bgList.splice(0, 1);

                var lastbg = this._bgList[this._bgList.length - 1];
                bg.setPositionY(lastbg.getPositionY() + lastbg.getContentSize().height);

                this._bgList.push(bg);

            }else{
                break;
            }
        }


    },


    addOneBackground:function(){

        var bg = null;
        if(this._bgList.length == 0){

            bg = this.createBackgroundByIndex(0);

            bg.setPosition(cc.p(0, 0));

        }else{

            var lastBackground = this._bgList[this._bgList.length - 1];
            var lastIndex = lastBackground.backgroundImgIndex;
            lastIndex = (lastIndex + 1) % this._bgImgList.length;
            bg = this.createBackgroundByIndex(lastIndex);

            bg.setPosition(cc.p(0, lastBackground.getPositionY() + lastBackground.getContentSize().height));
        }
        this.addChild(bg, 1);
        this._bgList.push(bg);


        return bg.getContentSize().height;
    },

    createBackgroundByIndex:function(index){

        var bg = new cc.Sprite(this._bgImgList[index]);

        bg.setAnchorPoint(cc.p(0, 0));
        bg.backgroundImgIndex = index;
        return bg;
    },




});